package com.xvaca.spcms.task;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.xvaca.spcms.bean.OrderBean;
import com.xvaca.spcms.bean.PipeBean;
import com.xvaca.spcms.bean.SyncDataBean;
import com.xvaca.spcms.cache.Cache;
import com.xvaca.spcms.dao.OrderDAO;
import com.xvaca.spcms.http.HttpRequester;
import com.xvaca.spcms.http.HttpRespons;

public class SyncDataTimerTask extends TimerTask {
	
	private static final Logger logger = Logger.getLogger(SyncDataTimerTask.class);

	@Override
	public void run() {
		
		// 获取待同步数据列表
		OrderDAO dao = new OrderDAO();
		List<SyncDataBean> list = dao.getSyncDate(100);
		logger.info("==========同步任务开始获取待同步数据[" + list.size() + "]条==========");
		
		
		for (SyncDataBean s : list) {
			
			String preMsg = "[order][id=" + s.getId() + "|cmd=" + s.getCmd() + "|payer=" + s.getPayer() + "|optime=" + s.getMoAt() + "|linkid=" + s.getLinkid() + "]";
			
			// 获取对应渠道
			PipeBean pipe = Cache.pipes.get(s.getPipeId());
			
			// 如果渠道信息不存在或已停止
			if (pipe == null || pipe.getStatus() == 0) {
				dao.updateOrderStatus(s.getId(), OrderBean.STATUS_STOP);
				logger.info(preMsg + "[status=" + OrderBean.STATUS_STOP + "]");
				continue;
			}
			
			// 如果是MO，且渠道不需要传MO
			if (s.getSmsStatus() == 3 && pipe.getNeedMO() == 0) {
				logger.debug("状态：3，MO同步：NO");
				dao.updateOrderStatus(s.getId(), OrderBean.STATUS_MO_UNSYNC);
				logger.info(preMsg + "[status=" + OrderBean.STATUS_MO_UNSYNC + "]");
				continue;
			} else if (s.getSmsStatus() == 4 && pipe.getNeedMO() == 1) {
				logger.debug("状态：4，MO同步：YES");
				OrderBean o = dao.getOrderByLinkid(s.getLinkid()); // 获取linkid所对应的mo
				logger.debug("STATUS:" + o.getStatus());
				if (o.getStatus() == OrderBean.STAUTS_DEDUCTION) {
					dao.updateOrderStatus(s.getId(), OrderBean.STAUTS_DEDUCTION);
					logger.info(preMsg + "[status=" + OrderBean.STAUTS_DEDUCTION + "]");
					continue;
				} else {
					// 同步
					boolean flag = this.sync(s, pipe.getSyncUrl());
					
					if (flag) {
						dao.updateOrderStatus(s.getId(), OrderBean.STATUS_SYNCED);
						logger.info(preMsg + "[status=" + OrderBean.STATUS_SYNCED + "]");
					} else {
						pipe.setSyncRecordErrorCount(pipe.getSyncRecordErrorCount() + 1);
						dao.updateOrderStatus(s.getId(), OrderBean.STATUS_EXCEPTION);
						logger.info(preMsg + "[status=" + OrderBean.STATUS_EXCEPTION + "]");
					}
					continue;
				}
			} else if (s.getSmsStatus() == 3 || s.getSmsStatus() == 4) {
				logger.debug("状态：" + s.getSmsStatus() + "，MO同步：" + pipe.getNeedMO());
				// 如果已同步50条以上而且扣量比例不为0，则按响应比例执行扣量
				logger.info("SyncTotal:" + pipe.getSyncRecordCount() + "|Deduction=" + pipe.getDeduction());
				int v = (int) (100 / pipe.getDeduction());
				if (pipe.getSyncRecordCount() > 50 && pipe.getDeduction() != 0) {
					 if (   pipe.getSyncRecordCount() % ( v )  == 0   ) {
						 dao.updateOrderStatus(s.getId(), OrderBean.STAUTS_DEDUCTION);
						 logger.info(preMsg + "[status=" + OrderBean.STAUTS_DEDUCTION + "]");
						 pipe.setSyncRecordCount(pipe.getSyncRecordCount() + 1);
						 continue;
					 }
				}
				
				// 同步
				boolean flag = this.sync(s, pipe.getSyncUrl());
				
				if (flag) {
					pipe.setSyncRecordCount(pipe.getSyncRecordCount() + 1);
					dao.updateOrderStatus(s.getId(), OrderBean.STATUS_SYNCED);
					logger.info(preMsg + "[status=" + OrderBean.STATUS_SYNCED + "]");
				} else {
					pipe.setSyncRecordErrorCount(pipe.getSyncRecordErrorCount() + 1);
					dao.updateOrderStatus(s.getId(), OrderBean.STATUS_EXCEPTION);
					logger.info(preMsg + "[status=" + OrderBean.STATUS_EXCEPTION + "]");
				}
			}
			
		}
		
		logger.info("=========================END===========================");
		System.out.println();

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int x = (int) (100/7.00);
		System.out.println(x);
	}
	
	public boolean sync(SyncDataBean data, String url) {
		
		HttpRequester request = new HttpRequester();
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("payer", data.getPayer());
		params.put("optime", data.getMoAt());
		params.put("linkid", data.getLinkid());
		params.put("content", data.getCmd());
		params.put("status", data.getSmsStatus() + "");
		
		try {
			HttpRespons res = request.sendPost(url, params);
			logger.info("[sync][" + url + "][payer=" + data.getPayer() + "&optime=" + data.getMoAt() + "&linkid=" + data.getLinkid() + "&content=" + data.getCmd() + "&status=" + data.getSmsStatus() + "][" + res.getContent() + "]");
		} catch (IOException e) {
			logger.error("同步数据异常", e);
			return false;
		}
		
		return true;
		
	}

}
